﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Zatify.WebUI.Infrastructure.Absrtact;
using System.Web.Security;
using Zatify.Domain.Abstract;
using Zatify.Domain.Data;
using System.Web.Script.Serialization;

namespace Zatify.WebUI.Infrastructure.Concrete
{
    public class ZatifyFormsAuthenticateProvider : IZatifyAuthProvider
    {
        private IZatifyRepository repository;

        private IZatifyUser _user;

        public ZatifyFormsAuthenticateProvider(IZatifyRepository repository)
        {
            this.repository = repository;
        }

        public bool AuthenticateUser(IZatifyUser user)
        {
            if (user.UserRole == (UserRole.SystemAdmin | UserRole.SystemUser))
            //if ((user.UserRole == UserRole.SystemAdmin) || (user.UserRole == UserRole.SystemUser))
            {
                this._user = this.repository.SystemUsers.FirstOrDefault(u => u.Login.ToLower() == user.Login.ToLower() && u.Password == user.Password);
            }
            else
            {
                var result = this.repository.LoginUser(user.Login, user.Password);

                if (result.IdResult == 1)
                {
                    switch (result.LoginType)
                    {
                        case "U":
                            this._user = this.repository.UserGetByToken(result.SecurityToken.Value);
                            user.UserRole = UserRole.RegularUser;
                            break;
                        case "B":
                            this._user = this.repository.BusinessUserGetByToken(result.SecurityToken.Value);
                            user.UserRole = UserRole.BusinessUser;
                            break;
                        default:
                            break;
                    }
                }
            }

            if (this._user != null)
            {
                this._user.TimeZoneOffset = user.TimeZoneOffset;

                SignIn(this._user, user.RememberUser);

                return true;
            }
            else
                return false;
        }

        public void LogOff()
        {
            FormsAuthentication.SignOut();
        }

        private void SignIn(IZatifyUser user, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(user.Login))
                throw new ArgumentException("Value cannot be null or empty.", "userName");

            var serializeModel = new ZatifyPrincipalSerializeModel()
            {
                Token = user.SecurityToken,
                Login = user.Login,
                UserRole = user.UserRole,
                ZipCode = user.ZipCode,
                TimeZoneOffset = user.TimeZoneOffset
            };

            var serializer = new JavaScriptSerializer();

            var userData = serializer.Serialize(serializeModel);

            var authTicket = new FormsAuthenticationTicket(
             1,
             user.Login,
             DateTime.Now,
             DateTime.Now.AddMinutes(15),
             createPersistentCookie,
             userData,
             FormsAuthentication.FormsCookiePath);

            var encTicket = FormsAuthentication.Encrypt(authTicket);
            var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            if (authTicket.IsPersistent)
                faCookie.Expires = authTicket.Expiration;

            HttpContext.Current.Response.Cookies.Add(faCookie);
        }
    }
}